<?php


namespace app\admin\model;

use GatewayClient\Gateway;

class CompReCompPurch extends Base
{
    /**
     * Desc: 部件中的外购件
     * User: 苏鹏
     * Date: 2023/10/24
     * Time: 10:53
     * @return void
     */
    public function componentInPurchased(int $id)
    {
        $comp_re_purchased = CompReCompPurch::where('component_id', $id)->field('comp_purch_id,number')->select()->toArray();
        if(!empty($comp_re_purchased))
        {
            foreach($comp_re_purchased as $key=>$val)
            {
                $compon_purcha_result = ComponentPurchased::where('id', $val['comp_purch_id'])->field('id,name,number,sn')->find();
                if(!empty($compon_purcha_result))
                {
                    $compon_purcha_result = $compon_purcha_result->toArray();
                    $comp_re_purchased[$key]['name'] = $compon_purcha_result['name'];
                    $comp_re_purchased[$key]['total_num'] = $compon_purcha_result['number'];
                    $comp_re_purchased[$key]['sn'] = $compon_purcha_result['sn'];
                }else{
                    $comp_re_purchased[$key]['name'] = '';
                    $comp_re_purchased[$key]['total_num'] = 0;
                    $comp_re_purchased[$key]['sn'] = '';
                }
            }
            return $comp_re_purchased;
        }else{
            return [];
        }
    }

    /**
     * Desc: 部件关联外购件 同时给予仓储部门发送消息
     * User: 苏鹏
     * Date: 2023/10/24
     * Time: 13:26
     * @return void
     */
    public function componentRePurchased(string $purchased, int $id, $is_update = 0)
    {
        //关联外购件
        $purchased = json_decode($purchased, true);
        if(!empty($purchased) && is_array($purchased))
        {
            $data = [];
            foreach($purchased as $k=>$v)
            {
                $data[] = [
                    'component_id' => $id,
                    'comp_purch_id' => $v['id'],
                    'number' => $v['num'],
                ];
            }

            if($is_update = 1)
            {
                $this->where('component_id', $id)->delete();    //删除上一次数据，重新保存
            }

            (new CompReCompPurch)->saveAll($data);
            //通知库房项目订单中外购件所需数量,返回消息内容
            $content = (new ComponentPurchased)->getToWarehouseNoticeContent($id, $purchased, $is_update);
            if(!empty($content))
            {
                $department_ids = get_config_cache('department_ids');
                $warehouse_dep_id = $department_ids['warehouse_dep_id']; //仓储部门
                $notice_data = [
                    'tmp_flag' => 'system', //消息模板标识
                    'to_dep_id' => $warehouse_dep_id, //发送的部门id
                    'content' => [
                        'data' => $content
                    ]
                ];
                event('SendNotice', $notice_data);
            }
        }
    }

}